require(["./config"], () => {
  require(["template", "header", "footer", "zoom"], template => {
    class Details {
      constructor() {
        this.getData();
      }
      getData() {
        //1.通过地址栏获取商品ID
        const id = window.location.search.slice(4);
        $.get(
          `http://www.xiongmaoyouxuan.com/api/detail?id=${id}&normal=1&sa=`,
          res => {
            this.renderList(res);
          }
        );
      }
      //2.发送请求获取数据
      renderList(res) {
        if (res.code === 200) {
          const {
            title,
            qunTitle,
            introduction,
            price,
            originPrice,
            accessoryHints,
            photo,
            id,
            expireMsg
          } = res.data.detail;

          $(".details_list").html(
            template("detailsDates", {
              title,
              qunTitle,
              introduction,
              price,
              originPrice,
              accessoryHints,
              photo,
              id,
              expireMsg
            })
          );
          //放大镜效果
          $(".zoom-image").elevateZoom({
            gallery: "pic_list"
          });
          this.addToCart(id, photo[0].url, title, originPrice, price);
        }
      }
      addToCart(id, imgUrl, title, originPrice, price) {
        console.log(123);
        $(".details_list").on("click", ".add_btn", () => {
          let info = null;
          if (localStorage.getItem("info")) {
            info = JSON.parse(localStorage.getItem("info"));
            let bool = false;
            info.forEach(function (item) {
              if (id == item.id) {
                item.count++;
                bool = true;
              }
              // else {
              //   const obj = { id, imgUrl, title, originPrice, price, count: 1 };
              //   info.push(obj);
              // }
            });
            if (bool) {
              //有商品信息
            } else {
              const obj = {
                id,
                imgUrl,
                title,
                originPrice,
                price,
                count: 1,
                check: true
              };
              info.push(obj);
            }
          } else {
            info = [
              { id, imgUrl, title, originPrice, price, count: 1, check: true }
            ];
          }
          localStorage.setItem("info", JSON.stringify(info));
          //显示加入成功四个字
          setTimeout(() => {
            $(".remind").animate({ opacity: 1 }, 500, "linear");
          }, 500);
        });
      }
    }
    return new Details();
  });
});
